<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>WebSocket</title>
</head>

<body>
  <h1>Chat Room</h1>
  <input type="text" id="sendTxt" />
  <button id="sendBtn">发送</button>
  <div id="recv"></div>
  <script>
    let websocket = new WebSocket("ws://localhost:3000/")

    function showMessage(str, type) {
      var div = document.createElement('div')
      div.innerHTML = str
      if (type == "enter") {
        div.style.color = "blue"
      } else if (type == "leave") {
        div.style.color = "red"
      }
      document.body.appendChild(div)
    }

    websocket.onopen = function () {
      console.log('websocket open')
      document.getElementById('recv').innerHTML = "Connected"
      document.getElementById('sendBtn').onclick = function () {
        let txt = document.getElementById('sendTxt').value
        if(txt) {
          websocket.send(txt)
        }
      }
    }
    websocket.onclose = function () {
      console.log('websocket close')
    }
    websocket.onmessage = function (e) {
      console.log(e.data)
      var msg = JSON.parse(e.data)
      showMessage(msg.data, msg.type)
    }
  </script>
</body>

</html>